import TableSelects from "@/component/common/tableSelects/tableSelects";
import { Button, Flex, Form, Input, Popconfirm } from "antd";
import MyTable from "@/component/common/myTable";
import { useMessageApi } from "@/component/context/messageContext/message";
import { useEffect, useMemo, useState } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import quesTypeApi from "./api";
import { MyDrawer } from "@/component/common/myDrawer";
import QuestionType from "@/component/common/questionType";

const columns: any = [
  {
    title: "名称",
    dataIndex: "name",
    key: "name",
    align: "center",
  },
];
function QuesType() {
  const navigate = useNavigate();
  const messageApi = useMessageApi();
  const location = useLocation();
  const [searchParams, setSearchParams] = useState({
    pageNum: 1,
    pageSize: 20,
    name: "",
  });
  const [currentQuesType, setCurrentQuesType] = useState<any>({});
  const [loading, setLoading] = useState<boolean>(false);
  const [selectedRowKeys, setSelectedRowKeys] = useState<number[]>([]);
  const [switchState, setSwitchState] = useState({
    isShowAdd: false,
    isShowEdit: false,
  });
  // 添加题型弹窗组件
  const AddQuesTypeDrawer = () => {
    const addQuesType = () => {
      quesTypeApi.addQuesType(currentQuesType).then(() => {
        messageApi.success("添加成功");
        setSwitchState((oldV) => {
          return { ...oldV, isShowAdd: false };
        });
        getQuesTypes(searchParams);
      });
    }
    return (
      <MyDrawer
        footer={
          <Flex gap={"1rem"} justify="right">
            <Button
              onClick={() => {
                setSwitchState((oldV) => {
                  return { ...oldV, isShowAdd: false };
                });
              }}
            >
              返回
            </Button>
            <Button
              htmlType="submit"
              onClick={() => {
                addQuesType()
              }}
            >
              保存
            </Button>
          </Flex>
        }
        open={switchState.isShowAdd}
        width={"80%"}
        onClose={() =>
          setSwitchState((oldV) => {
            return { ...oldV, isShowAdd: false };
          })
        }
      >
        <QuestionType state="QUESTYPE" content={currentQuesType} onChange={(value) => {
          setCurrentQuesType(value)
        }}></QuestionType>
      </MyDrawer>
    );
  };

  // 编辑题型弹窗组件
  const EditQuesTypeDrawer = () => {
    return (
      <MyDrawer
        footer={
          <Flex gap={"1rem"} justify="right">
            <Button
              onClick={() => {
                setSwitchState((oldV) => {
                  return { ...oldV, isShowEdit: false };
                });
              }}
            >
              返回
            </Button>
            <Button
              htmlType="submit"
              onClick={() => {
                updateQuesType(currentQuesType);
              }}
            >
              保存
            </Button>
          </Flex>
        }
        open={switchState.isShowEdit}
        width={"80%"}
        onClose={() =>
          setSwitchState((oldV) => {
            return { ...oldV, isShowEdit: false };
          })
        }
      >
        <QuestionType state="QUESTYPE" content={currentQuesType} onChange={(value) => {
          setCurrentQuesType(value)
        }}></QuestionType>
      </MyDrawer>
    );
  };

  // 过滤器组件
  const Filter = () => {
    const tableOptions = [
      {
        render: (
          <Input
            key="name"
            placeholder="请输入题型名"
            value={searchParams.name}
            allowClear
            onChange={(e) => {
              setSearchParams((oldV) => {
                return { ...oldV, name: e.target.value };
              });
            }}
          />
        ),
      },
    ];
    return (
      <TableSelects
        loading={loading}
        options={tableOptions}
        source={searchParams}
        onSearch={() => {
          navigate({
            search: `?pageNum=${searchParams.pageNum}&pageSize=${searchParams.pageSize}&name=${searchParams.name}`,
          });
        }}
        buttonChildren={
          <Flex gap={"10px"}>
            {selectedRowKeys.length > 0 && (
              <Popconfirm
                title={`确定删除这 ${selectedRowKeys.length} 个题型吗？`}
                onConfirm={() => {
                  delQuesType(selectedRowKeys);
                }}
              >
                <Button>删除</Button>
              </Popconfirm>
            )}
            <Button
              onClick={() => {
                setCurrentQuesType({
                  name: "",
                  data: [
                    {
                      type: "title",
                      value: "标题"
                    },
                    {
                      type: "judgment",
                      value: ""
                    }
                  ]
                });
                setSwitchState((oldV) => {
                  return { ...oldV, isShowAdd: true };
                });
              }}
            >
              添加
            </Button>
          </Flex>
        }
      ></TableSelects>
    );
  };
  const [quesTypeState, setQuesTypeState] = useState({
    tableData: [],
    total: 0,
  });
  // 获取题型列表api
  const getQuesTypes = (params: any) => {
    setLoading(true);
    quesTypeApi.getQuesType(params).then((data: any) => {
      setQuesTypeState((oldV) => {
        return { ...oldV, tableData: data.quesTypes, total: data.total };
      });
      setTimeout(() => {
        setLoading(false);
      }, 300);
    });
  };

  // 更新题型api
  const updateQuesType = (params: any) => {
    quesTypeApi.updateQuesType(params).then(() => {
      messageApi.success("更新成功");
      setSwitchState((oldV) => {
        return { ...oldV, isShowEdit: false };
      });
      getQuesTypes(searchParams);
    });
  };

  // 删除题型api
  const delQuesType = (ids: Array<number>) => {
    quesTypeApi.delQuesType(ids).then((data: any) => {
      messageApi.success("删除成功");
      getQuesTypes(searchParams);
    });
  };

  // 表格组件
  useEffect(() => {
    const searchParams = new URLSearchParams(location.search);
    const params = {
      pageNum: searchParams.get("pageNum")
        ? Number(searchParams.get("pageNum"))
        : 1,
      pageSize: searchParams.get("pageSize")
        ? Number(searchParams.get("pageSize"))
        : 20,
      name: searchParams.get("name") ? String(searchParams.get("name")) : "",
    };
    setSearchParams(params);
    getQuesTypes(params);
  }, [location.search]);
  const Table = useMemo(() => {
    const rowSelection = {
      onChange: (selectedRowKeys: any) => {
        setSelectedRowKeys(selectedRowKeys);
      },
      getCheckboxProps: (record: any) => ({
        disabled: false,
      }),
    };
    return (
      <MyTable
        loading={loading}
        rowSelection={rowSelection}
        rowKey={(record) => record.id}
        dataSource={quesTypeState?.tableData}
        columns={columns}
        pageSize={searchParams.pageSize}
        total={quesTypeState.total}
        onPaginationChange={(pageNum, pageSize) => {
          navigate({
            search: `?pageNum=${pageNum}&pageSize=${pageSize}&name=${searchParams.name}`,
          });
        }}
        onRow={(record) => ({
          onClick: () => {
            setCurrentQuesType({ ...record, data: JSON.parse(record.data) });
            setSwitchState((oldV) => {
              return { ...oldV, isShowEdit: true };
            });
          },
        })}
      ></MyTable>
    );
  }, [
    loading,
    navigate,
    quesTypeState?.tableData,
    quesTypeState.total,
    searchParams.name,
    searchParams.pageSize,
  ]);

  return (
    <>
      {AddQuesTypeDrawer()}
      {EditQuesTypeDrawer()}
      {Filter()}
      {Table}
    </>
  );
}

export default QuesType;
